// 1. React核心库
import React, { useState, useEffect } from 'react';

// 2. UI组件库 - 按字母顺序
import { Button, Card, Form, Input, InputNumber, Select, message } from 'antd';

// 4. 专业组件库
import { PageContainer } from '@ant-design/pro-components';

// 5. 路由和状态管理
import { useParams } from '@umijs/max';

// 7. 项目内部模块
import { apiClients } from '@/services/apiClient';
import { autoLoginInDev } from '@/utils/autoLogin';

// 8. 生成的类型定义 (必须使用，禁止手工定义)
import type { PermissionExtension, PermissionCategory } from '@/services/generated';

const { TextArea } = Input;

const PermissionForm: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [categories, setCategories] = useState<PermissionCategory[]>([]);
  const isEdit = !!id;

  useEffect(() => {
    loadCategories();
    if (isEdit && id) {
      const fetchData = async () => {
        try {
          await autoLoginInDev();
          const response = await apiClients.permissions.permissionsPermissionsRetrieve({ id: parseInt(id) });
          form.setFieldsValue(response.data);
        } catch (error) {
          message.error('获取数据失败');
        }
      };
      fetchData();
    }
  }, [id, isEdit, form]);

  const loadCategories = async () => {
    try {
      await autoLoginInDev();
      const response = await apiClients.permissions.permissionsCategoriesList({
        pageSize: 100,
      });
      setCategories(response.data?.items || []);
    } catch (error) {
      console.error('加载权限分类失败:', error);
    }
  };

  const onFinish = async (values: any) => {
    try {
      setLoading(true);
      await autoLoginInDev();

      if (isEdit) {
        await apiClients.permissions.permissionsPermissionsUpdate({ 
          id: parseInt(id!), 
          permissionExtensionRequest: values 
        });
        message.success('更新成功');
      } else {
        await apiClients.permissions.permissionsPermissionsCreate({ 
          permissionExtensionRequest: values 
        });
        message.success('创建成功');
      }

      window.location.href = '/permissions/permissions';
    } catch (error) {
      message.error(isEdit ? '更新失败' : '创建失败');
    } finally {
      setLoading(false);
    }
  };

  return (
    <PageContainer title={isEdit ? '编辑权限' : '新建权限'}>
      <Card>
        <Form
          form={form}
          layout="vertical"
          onFinish={onFinish}
          initialValues={{
            status: 'active',
            sort_order: 0,
          }}
        >
          <Form.Item
            label="所属模块"
            name="module"
            rules={[
              { required: true, message: '请输入所属模块' },
              { max: 50, message: '模块名不能超过50个字符' },
            ]}
          >
            <Input placeholder="请输入所属模块，如：auth、permissions" />
          </Form.Item>

          <Form.Item
            label="权限分类"
            name="category"
          >
            <Select
              placeholder="请选择权限分类"
              allowClear
              options={categories.map(cat => ({
                label: cat.name,
                value: cat.id,
              }))}
            />
          </Form.Item>

          <Form.Item
            label="资源路径"
            name="resource_path"
            rules={[
              { max: 200, message: '资源路径不能超过200个字符' },
            ]}
          >
            <Input placeholder="请输入资源路径，如：/admin/users/" />
          </Form.Item>

          <Form.Item
            label="API端点"
            name="api_endpoint"
            rules={[
              { max: 200, message: 'API端点不能超过200个字符' },
            ]}
          >
            <Input placeholder="请输入API端点，如：/api/users/" />
          </Form.Item>

          <Form.Item
            label="状态"
            name="status"
            rules={[{ required: true, message: '请选择状态' }]}
          >
            <Select
              options={[
                { label: '激活', value: 'active' },
                { label: '禁用', value: 'inactive' },
              ]}
            />
          </Form.Item>

          <Form.Item
            label="排序"
            name="sort_order"
            rules={[
              { type: 'number', min: 0, message: '排序值不能小于0' },
            ]}
          >
            <InputNumber
              min={0}
              max={999}
              placeholder="请输入排序值"
              style={{ width: '100%' }}
            />
          </Form.Item>

          <Form.Item
            label="描述"
            name="description"
            rules={[
              { max: 500, message: '描述不能超过500个字符' },
            ]}
          >
            <TextArea
              rows={4}
              placeholder="请输入权限描述"
            />
          </Form.Item>

          <Form.Item>
            <Button type="primary" htmlType="submit" loading={loading}>
              {isEdit ? '更新' : '创建'}
            </Button>
            <Button style={{ marginLeft: 8 }} href="/permissions/permissions">
              取消
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </PageContainer>
  );
};

export default PermissionForm;
